package com.gdzn.netty.service.impl;


import com.gdzn.common.core.utils.StringUtils;
import com.gdzn.netty.api.service.RemotePrepareOrderService;
import com.gdzn.netty.service.IDeviceRedisService;
import com.gdzn.netty.service.IDeviceService;
import com.gdzn.signal.service.RemoteSignalService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @created: 2024-04-15
 * @version: V1.0
 */
@Slf4j
@Component
public class DeviceServiceImpl implements IDeviceService {

    @Autowired
    private IDeviceRedisService deviceRedisService;

    @Autowired
    private RemoteSignalService remoteSignalService;

    @Autowired
    private RemotePrepareOrderService remotePrepareOrderService;


    /**
     * 解析并且保存设备上报的数据
     * @param msgType
     * @param msg
     */
    @Async
    @Override
    public void sendDataToSave(Integer msgType, Object msg) {
        try {
            log.info("***sendDataToSave***msgType:{},msg:{}",msgType,msg);
            remoteSignalService.insert(msg.toString());
            //退电关闭仓门后有告警数据上报，这个时候生成话单(废弃)
//            if(DeviceMsgEnum.ALARM_REPOT.getMsgType()==msgType){
//                remotePrepareOrderService.add(msg.toString());
//            }
        }catch (Exception e){
            log.info("******sendDataToSave***Exception**Exception**");
        }
        log.info("***sendDataToSave***msgType****end");
    }

    /**
     * 更改电柜设备在线和离线状态
     * @param devId
     * @param online
     */
    @Async
    @Override
    public void updateCabinetOnline(String devId, String online) {
        log.info("***updateCabinetOnline***devId:{};online:{}",devId,online);
        if(!StringUtils.isEmpty(devId)){
            remoteSignalService.updateCabinetOnline(devId,online);
        }
    }

    /**
     * 删除通道
     * @param ctx
     */
    @Override
    public void removeChannel(ChannelHandlerContext ctx) {
//        String channelId = ctx.channel().id().asShortText();
//        String devId = deviceRedisService.getDevIdByChannelId(channelId);
//        updateCabinetOnline(devId, 0);
        //关闭通道会触发TcpDevicelHandler.handlerRemoved通道移除方法
        deviceRedisService.removeChannel(ctx);
    }

    /**
     * 设置设备ID和通道ID等相关数据到redis缓存
     * @param devId
     * @param channelId
     */
    @Override
    public void setChannelIdAndDevIdRedis(String devId, String channelId) {
        deviceRedisService.setChannelIdByDevId(devId,channelId);
        deviceRedisService.setDevIdByChannelId(channelId, devId);
    }

    /**
     * 移除设备ID和通道ID等相关数据到redis缓存
     * @param devId
     * @param channelId
     */
    @Override
    public void removeChannelIdAndDevIdRedis(String devId, String channelId) {
        deviceRedisService.removeChannelIdByDevId(devId);
        deviceRedisService.removeDevIdByChannelId(channelId);
    }
}
